<template>
  <div class="content">
    <div class="content-head">
      <div class="head-left">
        <span class="left-tip">欢迎，{{ username }}</span>
      </div>
      <div class="head-right">
        <span class="right-time">{{ real_time }}</span>
      </div>
      <!--
        <svg-icon icon-class="person" width="50px" height="30px" style="cursor: pointer;" title="查看个人信息"></svg-icon>
      -->
    </div>
    <div class="content-main">
      <div class="main-top">
        <div class="top-item item1">
          <div class="item-title">
            <span class="title-tip">工单总数</span>
          </div>
          <div class="item-content">
            <span class="content-text">{{ orderInfo.totalQuantity }}</span>
          </div>
        </div>
        <div class="top-item item2">
          <div class="item-title">
            <span class="title-tip">已完成数</span>
          </div>
          <div class="item-content">
            <span class="content-text">{{ orderInfo.finishedQuantity }}</span>
          </div>
        </div>
        <div class="top-item item3">
          <div class="item-title">
            <span class="title-tip">未完成数</span>
          </div>
          <div class="item-content">
            <span class="content-text">{{ orderInfo.unFinishedQuantity }}</span>
          </div>
        </div>
      </div>
      <div class="main-chart">
        <div class="chart-title">
          <span class="title-tip">工时统计</span>
        </div>
        <div class="chart-item"></div>
      </div>
    </div>
    <div class="content-footer"></div>
    <!-- 个人信息dialog -->
    <el-dialog title="个人信息" :visible.sync="personInfoDialog" width="40%" @close="dialogFormCancel" :close-on-click-modal="false">
      <el-form label-position="right" label-width="80px" ref="dialogForm" :model="dialogForm" :rules="dialogFormRules" size="small" style="width:80%;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="dialogForm.username" :disabled="dialogForm.isDisabledUsernameInput" placeholder="请输入用户名，支持字母、数字、_下划线，长度不少于5位"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="dialogForm.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="dialogForm.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="dialogForm.mobile" @input="dialogForm.mobile = String(dialogForm.mobile).replace(/[^0-9]/g,'')" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="修改密码">
          <el-switch v-model="dialogForm.isEditPwd"></el-switch>
        </el-form-item>
        <template v-if="dialogForm.isEditPwd">
          <el-form-item label="新密码" prop="newPwd">
            <el-input v-model="dialogForm.newPwd" placeholder="请输入新密码"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormCancel" size="small">取消</el-button>
        <el-button type="primary" @click="dialogFormConfirm" size="small">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getInfo, reqUpdateUser, reqOrderQuantityInfo, reqWorkTimeInfo } from "@/api/user.js";
import * as echarts from 'echarts';
import { getNowTime } from "@/utils/tools.js";
export default {
  name: 'Dashboard',
  data(){
    const validate1 = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_]{5,}$/;
      if (value.trim() === '') {
        callback(new Error('请输入用户名'));
      } else if(!regex.test(value)) {
        callback(new Error("请输入合法的用户名，支持字母、数字和下划线，长度不少于5位"));
      } else if (regex.test(value)){
        callback();
      }
    };
    const validate2 = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入姓名'));
      } else if(value.trim().length < 2) {
        callback(new Error("姓名不能少于两个字符"));
      } else {
        callback();
      }
    };
    const validate3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择性别'));
      } else {
        callback();
      }
    };
    const validate4 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入年龄'));
      } else if(Number(value) > 130){
        callback(new Error('您是吃了唐僧吗'));
      } else if(Number(value) < 1){
        callback(new Error('年龄太小了'));
      } else {
        callback();
      }
    };
    const validate5 = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入手机号'));
      } else if(value.trim().length !== 11){
        callback(new Error("手机号码格式错误"));
      } else {
        callback();
      }
    };
    const validate6 = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_]{6,}$/;
      if (value.trim() === '') {
        callback(new Error('请输入新密码'));
      } else if(!regex.test(value)){
        callback(new Error('密码只能为字母、数字和下划线_，长度不能少于6位'));
      } else {
        callback();
      }
    };
    return {
      orderInfo:{
        totalQuantity:0,
        finishedQuantity:0,
        unFinishedQuantity:0
      },
      dialogForm:{
        id:"",
        username:"",
        name:"",
        sex:"",
        age:"",
        mobile:"",
        newPwd:"",
        isEditPwd:false,
        isDisabledUsernameInput:false
      },
      dialogFormRules:{
        username: [{require:true, validator: validate1, trigger: 'blur' }],
        name: [{require:true, validator: validate2, trigger: 'blur' }],
        sex: [{require:true, validator: validate3, trigger: 'change' }],
        age: [{require:true, validator: validate4, trigger: 'blur' }],
        mobile: [{require:true, validator: validate5, trigger: 'blur' }],
        newPwd:[{require:true, validator: validate6, trigger: 'blur' }]
      },
      myChart:null,
      real_time:"1970年01月01日 00:00:00",
      timer_realTime:null
    }
  },
  mounted(){
    this.getWorkTimeInfo();
    this.getStockInfo();
    this.initEchart();
    const _this = this;
    window.addEventListener("resize",_this.windowSizeChangeEvent);
    this.showRealTime();
  },
  watch:{
    personInfoDialog:{
      handler(newVal,oldVal){
        if(newVal){
          this.getUserInfo();
        }
      },
      immediate:true
    }
  },
  beforeDestroy(){
    const _this = this;
    window.removeEventListener("resize",_this.windowSizeChangeEvent);
    clearInterval(this.timer_realTime);
  },
  computed: {
    ...mapGetters(['username','personInfoDialog'])
  },
  methods:{
    //获取用户信息
    async getUserInfo(){
      let username = this.username;
      try{
        let res = await getInfo(null,username);
        if(res.data.code === 200){
          const { id, userName, name, sex, age, mobile, interned } = res.data.data[0];
          this.dialogForm.username = userName;
          this.dialogForm.name = name;
          this.dialogForm.sex = sex;
          this.dialogForm.age = age;
          this.dialogForm.mobile = mobile;
          this.dialogForm.id = id;
          //admin用户禁止编辑用户名
          if(interned){
            this.dialogForm.isDisabledUsernameInput = true;
          }
        }
        console.log('获取用户信息api',res);
      }catch(error){
        this.$message({type:"error",message:"用户信息获取异常:" + error.response.data.message});
      }
    },
    //获取工单生产完成情况
    async getStockInfo(){
      reqOrderQuantityInfo().then(response => {
        if(response.data.code === 200){
          const { totalQuantity, finishQuantity, unFinishQuantity } = response.data.data;
          this.orderInfo.totalQuantity = totalQuantity;
          this.orderInfo.finishedQuantity = finishQuantity;
          this.orderInfo.unFinishedQuantity = unFinishQuantity;
        }
      }).catch(error => {
        this.$message({type:"error",message:"工单信息获取失败"});
      })
    },
    dialogFormCancel(){
      this.$store.dispatch("user/openOrClosePersonInfoDialog",false);
      this.dialogForm.id = "";
      this.dialogForm.username = "";
      this.dialogForm.name = "";
      this.dialogForm.sex = "";
      this.dialogForm.age = "";
      this.dialogForm.mobile = "";
      this.dialogForm.oldPwd = "";
      this.dialogForm.newPwd = "";
      this.dialogForm.isEditPwd = false;
      this.dialogForm.isDisabledUsernameInput = false;
      this.$refs.dialogForm.clearValidate();
    },
    dialogFormConfirm(){
      let validateResult = [];
      let validateField = ['username','name','sex','age','mobile','newPwd'];
      this.dialogForm.isEditPwd ? '' : validateField = validateField.slice(0,5);
      this.$refs.dialogForm.validateField(validateField,(result) => {
        result === "" ? validateResult.push(true) : validateResult.push(false);
      })
      if(validateResult.every(e => e === true)){
        //校验通过
        const { id,username,name,sex,age,mobile,newPwd } = this.dialogForm;
        const paramters = {id,userName:username,name,sex,age,mobile};
        this.dialogForm.isEditPwd ? paramters.password = newPwd : '';
        reqUpdateUser(paramters).then(async response => {
          if(response.data.code === 200){
            if(this.dialogForm.isEditPwd){
              //修改了密码退出登录
              this.$message({type:"info",message:"密码修改成功,即将跳转到登录页..."});
              const _this = this;
              setTimeout(async () => {
                await _this.$store.dispatch('user/logout');
                await _this.$store.dispatch("permission/resetState");
                _this.$router.push(`/login?redirect=${this.$route.fullPath}`);
              },500)
            } else {
              this.$message({type:"success",message:"用户信息更新成功!"});
              this.$router.go(0);
            }
            this.dialogFormCancel();
          }
        }).catch(error => {
          this.$message({type:"error",message:"用户信息更新失败:" + error.response.data.message});
        })
      } else {
        //校验不通过
        this.$message({type:"error",message:"请将表单填写完整"});
      }
    },
    initEchart(){
      const chartDom = document.querySelector(".chart-item");
      this.myChart = echarts.init(chartDom);
      const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
      const hours = [8, 8, 10, 12, 9, 0, 0];
      const option = {
        xAxis: {
          type: 'category',
          data: days
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: hours,
            type: 'line',
            areaStyle:{
              color:"#9ed4e8",
              shadowColor: '#9195a3',
              shadowBlur: 10
            }
          }
        ]
      };
      option && this.myChart.setOption(option);
    },
    //获取近七天工时完成情况
    getWorkTimeInfo () {
      reqWorkTimeInfo().then(response => {
        if(response.data.code === 200){
          let days = [], hours = [];
          for(let i = 0; i < response.data.data.length; i ++){
            days.push(response.data.data[i].checkDate);
            hours.push(response.data.data[i].hoursDifference);
          }
          const option = {
            xAxis: { type: 'category', data: days},
            yAxis: { name:'工时/H', type: 'value'},
            series: [ { data: hours,type: 'line',areaStyle:{ color:"#9ed4e8",shadowColor: '#9195a3',shadowBlur: 10 },itemStyle: { emphasis: {label: {show: true,position: 'top',formatter: '{c}'}}}}]
          };
          this.myChart.setOption(option);
        }
        console.log("查询工时api",response);
      }).catch(error => {
        this.$message({type:"error",message:"工时查询失败"})
      })
    },
    windowSizeChangeEvent(){
      this.myChart.resize();
    },
    //显示实时时间
    showRealTime:function(){
      if(this.timer_realTime !== null) clearInterval(this.timer_realTime);
      this.timer_realTime = setInterval(() => {
        this.real_time = getNowTime();
      },1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.content{
  width: 100%;
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
  padding: 5px 15px;
  box-sizing: border-box;
    .content-head{
      width: 100%;
      height: 10%;
      padding: 0;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      .head-left{
        display: flex;
        align-items: center;
      }
      .head-right{
        display: flex;
        .right-time{
          font-size: 12px;
          color: #9195a3;
        }
      }
    }
    .content-main{
      width: 100%;
      height: 88%;
      .main-top{
        width: 100%;
        height: 30%;
        display: flex;
        justify-content: space-between;
        .top-item{
          width: 30%;
          height: 100%;
          display: flex;
          flex-direction: column;
          border-radius: 10px;
          background-image: linear-gradient(45deg, #111FE5, #79B2EC);
          .item-title{
            width: 100%;
            height: 40%;
            box-sizing: border-box;
            border-bottom: 1px solid #fff;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
          }
          .item-content{
            width: 100%;
            height: 60%;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
          }
        }
        .item2{
          background-image: linear-gradient(45deg, #e4fe18, #1dffb6);
        }
        .item3{
          background-image: linear-gradient(45deg, #8ca9c8, #f38496);
        }
      }
      .main-chart{
        width: 100%;
        height: 70%;
        display: flex;
        flex-direction: column;
        .chart-title{
          width: 100%;
          height: 10%;
          display: flex;
          align-items: center;
          .title-tip{
            padding-right: 5px;
            font-size: 14px;
            font-weight: 600;
            border-right: 5px solid #9195a3;
          }
        }
        .chart-item{
          width: 100%;
          height: 90%;
          background: #f3f4fa;
          border-radius: 10px;
        }
      }
    }
    .content-footer{
      width: 100%;
      height: 2%;
    }
}
</style>
